login = false;
userid = null;
chat_refresh = false;
msg_ids = [];
$(document).ready(function(){
                
    $.getJSON('../isloggedin', function(data) {
        if(data.login == true){
            login = true;
            userid = data.id;
            console.log("login="+ login );
            console.log("userid="+ userid );
            setlogin();
        }else{
            $("#logout").hide();
        }
        renderPage();
                    
    });  
            
    $("#logout").click(function(){
        $.getJSON('../logout', function(data){
            if(data.logout == true){
                chat = false;
                $("#logout").hide();  
                $("#chat").hide();
                $("#menu").hide();
                $("#search").hide();
                $("#content").load("login.html");
            } 
        });
    });
    $( "#create_chat" ).click(function() {
        $( "#create-chat-form" ).dialog( "open" );
    }); 

    
    $("#msg").keypress(function(e)
    {
        
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13)
        {
            sendMessage();
            e.preventDefault();
        }
    });
            
    $( "#create-chat-form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Create": function() {
                $.post('../create_chat',$("#create-chat").serialize(), function(data) {
                    var data = jQuery.parseJSON(data);
                    if(data.created == true){
                        getChatList();
                        $("#create-chat-form").dialog( "close" );
                    }else{
                        $("#chat-error").html(data.error);
                    }
                });                    
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
                    
        }
    });

    $('.searchField').keypress(function (e) {
        if (e.which == 13) {
            search = $(this).val();
            window.location="?page=search&search="+search;
        }
    });
});